<template>
  <div class="merchant-menu">
    <div class="page-header">
      <h2>菜单管理</h2>
      <el-button type="primary" @click="showAddDialog = true">
        <el-icon><Plus /></el-icon>
        添加菜品
      </el-button>
    </div>
    
    <div class="menu-content">
      <el-row :gutter="20">
        <el-col
          v-for="item in menuItems"
          :key="item.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
        >
          <el-card class="menu-item-card" shadow="hover">
            <div class="menu-item-image">
              <el-image
                :src="item.imageUrl || '/default-food.jpg'"
                fit="cover"
                class="image"
              >
                <template #error>
                  <div class="image-placeholder">
                    <el-icon><Food /></el-icon>
                  </div>
                </template>
              </el-image>
              
              <div class="item-actions">
                <el-button
                  type="primary"
                  size="small"
                  circle
                  @click="editItem(item)"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  circle
                  @click="deleteItem(item.id)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
              
              <div class="item-status">
                <el-switch
                  v-model="item.available"
                  @change="toggleAvailability(item)"
                  active-text="上架"
                  inactive-text="下架"
                />
              </div>
            </div>
            
            <div class="menu-item-info">
              <h4 class="item-name">{{ item.name }}</h4>
              <p class="item-description">{{ item.description }}</p>
              
              <div class="item-meta">
                <div class="price">¥{{ item.price }}</div>
                <div class="stock">库存: {{ item.stock }}</div>
              </div>
              
              <div class="item-category">
                <el-tag size="small">{{ item.categoryName }}</el-tag>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <div v-if="menuItems.length === 0" class="empty-state">
        <el-empty description="暂无菜品" />
      </div>
    </div>
    
    <!-- 添加/编辑菜品对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="isEdit ? '编辑菜品' : '添加菜品'"
      width="600px"
    >
      <el-form
        ref="menuFormRef"
        :model="menuForm"
        :rules="menuRules"
        label-width="100px"
      >
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="menuForm.name" placeholder="请输入菜品名称" />
        </el-form-item>
        
        <el-form-item label="菜品描述" prop="description">
          <el-input
            v-model="menuForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入菜品描述"
          />
        </el-form-item>
        
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="menuForm.price"
            :min="0"
            :precision="2"
            :step="0.1"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="库存" prop="stock">
          <el-input-number
            v-model="menuForm.stock"
            :min="0"
            :precision="0"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="分类" prop="categoryId">
          <el-select
            v-model="menuForm.categoryId"
            placeholder="请选择分类"
            style="width: 100%"
          >
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="图片">
          <el-upload
            class="image-upload"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
          >
            <img v-if="menuForm.imageUrl" :src="menuForm.imageUrl" class="upload-image" />
            <el-icon v-else class="upload-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="是否上架">
          <el-switch v-model="menuForm.available" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="saveMenuItem" :loading="saving">
            {{ isEdit ? '更新' : '添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Food } from '@element-plus/icons-vue'
import { getMenuItemsByMerchant, createMenuItem, updateMenuItem, deleteMenuItem, toggleMenuItemAvailability } from '../../api/menu'
import { getCategories, getMyMerchant } from '../../api/merchant'

const menuItems = ref([])
const categories = ref([])
const merchantInfo = ref(null)
const showAddDialog = ref(false)
const isEdit = ref(false)
const saving = ref(false)

const menuForm = reactive({
  id: null,
  name: '',
  description: '',
  price: 0,
  stock: 0,
  categoryId: '',
  imageUrl: '',
  available: true
})

const menuRules = {
  name: [
    { required: true, message: '请输入菜品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '菜品名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入菜品描述', trigger: 'blur' },
    { max: 200, message: '菜品描述不能超过 200 个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格必须大于等于0', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存必须大于等于0', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ]
}

const loadMenuItems = async () => {
  try {
    // 先获取当前商家信息
    if (!merchantInfo.value) {
      await loadMerchantInfo()
    }
    
    if (merchantInfo.value && merchantInfo.value.id) {
      console.log('开始加载菜单，商家ID:', merchantInfo.value.id)
      const response = await getMenuItemsByMerchant(merchantInfo.value.id)
      menuItems.value = response.data
      console.log('菜单加载成功，数量:', menuItems.value.length)
    } else {
      console.error('无法获取商家信息:', merchantInfo.value)
      ElMessage.error('无法获取商家信息')
    }
  } catch (error) {
    console.error('加载菜单失败:', error)
    ElMessage.error('加载菜单失败')
  }
}

const loadMerchantInfo = async () => {
  try {
    const response = await getMyMerchant()
    merchantInfo.value = response.data
    console.log('商家信息加载成功:', merchantInfo.value)
  } catch (error) {
    console.error('加载商家信息失败:', error)
    ElMessage.error('加载商家信息失败')
  }
}

const loadCategories = async () => {
  try {
    const response = await getCategories()
    categories.value = response.data
  } catch (error) {
    ElMessage.error('加载分类失败')
  }
}

const resetForm = () => {
  Object.assign(menuForm, {
    id: null,
    name: '',
    description: '',
    price: 0,
    stock: 0,
    categoryId: '',
    imageUrl: '',
    available: true
  })
}

const editItem = (item) => {
  isEdit.value = true
  Object.assign(menuForm, { ...item })
  showAddDialog.value = true
}

const deleteItem = async (itemId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个菜品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteMenuItem(itemId)
    ElMessage.success('删除成功')
    loadMenuItems()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const toggleAvailability = async (item) => {
  try {
    await toggleMenuItemAvailability(item.id)
    ElMessage.success(item.available ? '已上架' : '已下架')
  } catch (error) {
    ElMessage.error('操作失败')
    item.available = !item.available // 恢复原状态
  }
}

const saveMenuItem = async () => {
  try {
    await menuFormRef.value.validate()
    saving.value = true
    
    // 确保有商家ID
    if (!merchantInfo.value || !merchantInfo.value.id) {
      ElMessage.error('无法获取商家信息')
      return
    }
    
    if (isEdit.value) {
      await updateMenuItem(menuForm.id, menuForm)
      ElMessage.success('更新成功')
    } else {
      await createMenuItem(merchantInfo.value.id, menuForm)
      ElMessage.success('添加成功')
    }
    
    showAddDialog.value = false
    loadMenuItems()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
  } finally {
    saving.value = false
  }
}

const handleImageSuccess = (response) => {
  menuForm.imageUrl = response.data
}

const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const menuFormRef = ref()

onMounted(async () => {
  await loadMerchantInfo()
  await loadMenuItems()
  await loadCategories()
})
</script>

<style scoped>
.merchant-menu {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
}

.menu-content {
  margin-top: 20px;
}

.menu-item-card {
  margin-bottom: 20px;
  position: relative;
}

.menu-item-image {
  position: relative;
  height: 200px;
  overflow: hidden;
  border-radius: 8px;
}

.image {
  width: 100%;
  height: 100%;
}

.image-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #f5f5f5;
  color: #909399;
  font-size: 48px;
}

.item-actions {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  gap: 5px;
}

.item-status {
  position: absolute;
  bottom: 10px;
  right: 10px;
}

.menu-item-info {
  padding: 15px 0;
}

.item-name {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.item-description {
  margin: 0 0 12px 0;
  color: #7f8c8d;
  font-size: 14px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.price {
  font-size: 18px;
  font-weight: 600;
  color: #f56c6c;
}

.stock {
  font-size: 14px;
  color: #7f8c8d;
}

.item-category {
  margin-top: 10px;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

.image-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-image {
  width: 178px;
  height: 178px;
  display: block;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
}
</style>
